<template>
	<div class="import-files flex c-content">
		<div class="upload-area" :class="{'is-step': $store.getters.stepIndex === '2-3'}">
			<!-- <Upload 
				multiple 
				name="xlsx" 
				type="drag"
				ref="upload"
				:max-size="1500"  
				:action="uploadUrl" 
				:format="['xlsx', 'xls']" 
				:show-upload-list="true" 
				:headers="{Authorization: '7c1cb7ee44ce6e8c7288a0aea11efcd04df40c1e5fe4b9408ebdb876a2ef3015'}"
				:on-error="onError"
				:on-remove="onRemove"
				:on-success="onSuccess"
				:on-progress="onProgress"
				:before-upload="beforeUpload"
				:on-format-error="onFormatError"
				:on-exceeded-size="onExceededSize"
				
			> -->
				<!-- :class="classes" -->
			<div
				:class="classes"
				@click="handleClick"
				@drop.prevent="onDrop"
				@dragover.prevent="dragOver = true"
				@dragleave.prevent="dragOver = false">
				<input
					ref="input"
					type="file"
					:class="[prefixCls + '-input']"
					@change="handleChange"
					:multiple="multiple"
					:accept="accept">
				<div class="upload-area-slot">
					<i class="iconfont icon-shangchuan"></i>
					<p class="content-title">点击或将文件拖拽到这里上传</p>
					<p class="content-text">支持扩展名：.xls、xlsx.（非标准结算单上传后，系统需要1-2天时间进行数据转换）</p>
				</div>
			</div>
			<!-- </Upload> -->
		</div>
		<div class="upload-list">
			<div class="list-title">上传记录（{{successCount}} / {{fileList.length}}）</div>
			<div class="list-content">
				<div v-for="(item, index) in fileList" :key="index" class="list-item">
					<div class="item-detail flex">
						<div class="file-icon">
							<i class="iconfont icon-chaxun"></i>
						</div>
						<div class="file-name" :title="item.name">
							{{item.name}}
						</div>
						<div class="action-icon">
							<i class="iconfont icon-shuaxin" v-show="item.status === 'wrong'" @click="handleRemove(item)"></i>
							<i class="iconfont icon-jiantou-xia" v-show="item.status === 'success'"></i>
						</div>
					</div>
					<div class="item-progress">
						<Progress 
                            hide-info 
                            :stroke-width="2" 
                            v-show="item.showProgress" 
                            :status="item.status"
                            :percent="item.status === 'wrong' ? 99.99 : item.percentage" >
                        </Progress>
					</div>
					<div v-show="item.status === 'wrong'" class="item-tip">{{item.tip}}</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
    import ajax from 'commons/js/ajax';
    const prefixCls = 'ivu-upload';
	export default {
        name: 'importVehicle',
        props: {
			action: {
                type: String,
                // required: true
            },
            headers: {
                type: Object,
                default () {
                    return {};
                }
            },
            multiple: {
                type: Boolean,
                default: false
            },
            data: {
                type: Object
            },
            name: {
                type: String,
                default: 'file'
            },
            withCredentials: {
                type: Boolean,
                default: false
            },
            showUploadList: {
                type: Boolean,
                default: true
            },
            type: {
                type: String,
                validator (value) {
					function oneOf(value, validList){
						for (let i = 0; i < validList.length; i++) {
							if (value === validList[i]) {
								return true;
							}
						}
						return false;
					}   
                    return oneOf(value, ['select', 'drag']);
                },
                default: 'select'
            },
            format: {
                type: Array,
                default () {
                    return [];
                }
            },
            accept: {
                type: String
            },
            maxSize: {
                type: Number
            },
            beforeUpload: Function,
            onProgress: {
                type: Function,
                default () {
                    return {};
                }
            },
            onSuccess: {
                type: Function,
                default () {
                    return {};
                }
            },
            onError: {
                type: Function,
                default () {
                    return {};
                }
            },
            onRemove: {
                type: Function,
                default () {
                    return {};
                }
            },
            onPreview: {
                type: Function,
                default () {
                    return {};
                }
            },
            onExceededSize: {
                type: Function,
                default () {
                    return {};
                }
            },
            onFormatError: {
                type: Function,
                default () {
                    return {};
                }
            },
            defaultFileList: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
		// todo 引入token
		data() {
			return {
                prefixCls: prefixCls,
                dragOver: false,
                fileList: [],
                tempIndex: 1
			}
		},
		mounted() {

		},
        computed: {
            classes () {
                return [
                    `${prefixCls}`,
                    {
                        [`${prefixCls}-select`]: this.type === 'select',
                        [`${prefixCls}-drag`]: this.type === 'drag',
                        [`${prefixCls}-dragOver`]: this.type === 'drag' && this.dragOver
                    }
                ];
            },
			successCount(){
				let i = 0;
				this.fileList.forEach(item => {
					if(item.status === 'success'){
						i++
					}
				})
				return i;
			}
        },
		methods: {
            handleClick () {	// 点击div触发input点击事件
                if(this.$store.getters.stepIndex === '2-3') return;

                this.$refs.input.click();
            },
            handleChange (e) {	// input change 事件
                if(this.$store.getters.stepIndex === '2-3') return;

                const files = e.target.files;

                if (!files) {
                    return;
                }
                this.uploadFiles(files);
                this.$refs.input.value = null;
            },
            onDrop (e) { // 拖拽事件
                this.dragOver = false;
                this.uploadFiles(e.dataTransfer.files);
            },
            uploadFiles (files) {

                let postFiles = Array.prototype.slice.call(files);
                if (!this.multiple) postFiles = postFiles.slice(0, 1);

                if (postFiles.length === 0) return;

                postFiles.forEach(file => {
                    this.upload(file);
                });
            },
            upload (file) {
                if (!this.beforeUpload) {
                    return this.post(file);
                }

                const before = this.beforeUpload(file);
                if (before && before.then) {
                    before.then(processedFile => {
                        if (Object.prototype.toString.call(processedFile) === '[object File]') {
                            this.post(processedFile);
                        } else {
                            this.post(file);
                        }
                    }, () => {
                        // this.$emit('cancel', file);
                    });
                } else if (before !== false) {
                    this.post(file);
                } else {
                    // this.$emit('cancel', file);
                }
            },
            post (file) {
				let _file = this.handleStart(file);
                // 验证 格式
                if (this.format.length) {
                    const _file_format = file.name.split('.').pop().toLocaleLowerCase();
                    const checked = this.format.some(item => item.toLocaleLowerCase() === _file_format);
                    if (!checked) {
						_file.tip = "请上传xls或xlsx格式的文件";
				        _file.status = 'wrong';
                        this.onFormatError(_file, this.fileList);
                        return false;
                    }
                }

                // 验证 大小
                if (this.maxSize) {
                    if (file.size > this.maxSize * 1024) {
						_file.tip = "超出大小限制";
				        _file.status = 'wrong';
                        this.onExceededSize(_file, this.fileList);
                        return false;
                    }
                }

				
                // let formData = new FormData();
				// formData.append(this.name, file);
				this.startUpload(_file, _file.action);
			},
			startUpload(_file, action){
                ajax({
                    headers: this.headers,
                    withCredentials: this.withCredentials,
                    file: _file.file,
                    data: this.data,
                    filename: this.name,
                    action: action,
                    onProgress: e => {
                        this.handleProgress(e, _file.file);
                    },
                    onSuccess: res => {
                        this.handleSuccess(res, _file.file, '上传成功 (已标准)');
                    },
                    onError: (err, response) => {
                        this.handleError(err, response, _file.file);
                    }
                });
			},
            handleStart (file) {
                file.uid = Date.now() + this.tempIndex++;
                const _file = {
					file: file,
                    status: 'normal',
                    name: file.name,
                    size: file.size,
                    percentage: 0,
					uid: file.uid,
					action: this.action,
                    showProgress: true
                };

				this.fileList.push(_file);
				return _file;
            },
            getFile (file) {
                const fileList = this.fileList;
                let target;
                fileList.every(item => {
                    target = file.uid === item.uid ? item : null;
                    return !target;
				});
                return target;
            },
            handleProgress (e, file) {
                const _file = this.getFile(file);
                this.onProgress(e, _file, this.fileList);
                _file.percentage = e.percent === 100 ? 99.99 : (e.percent|| 0);
            },
            handleSuccess (res, file, tip) {
                const _file = this.getFile(file);

                if (_file) {
                    setTimeout(()=>{
                        _file.showProgress = false;
                    }, 1000);
                    setTimeout(() => {
                        _file.percentage = 100;
                        _file.status = 'success';
                    }, 300);
                    _file.response = res;
					_file.tip = tip;
                    // this.dispatch('FormItem', 'on-form-change', _file);
                    this.onSuccess(res, _file, this.fileList);

                }
            },
            handleError (err, response, file) {
                const _file = this.getFile(file);
                const fileList = this.fileList;

				_file.status = 'wrong';
				_file.tip = "上传失败，请重试";

                fileList.splice(fileList.indexOf(_file), 1);

                this.onError(err, response, file);
            },
            handleRemove(file) {
                const fileList = this.fileList;
                fileList.splice(fileList.indexOf(file), 1);
                this.onRemove(file, fileList);
            },
            handlePreview(file) {
                if (file.status === 'success') {
                    this.onPreview(file);
                }
            },
            clearFiles() {
                this.fileList = [];
            }
        },
        watch: {
            defaultFileList: {
                immediate: true,
                handler(fileList) {
                    this.fileList = fileList.map(item => {
                        item.status = 'success';
                        item.percentage = 100;
                        item.uid = Date.now() + this.tempIndex++;
                        return item;
                    });
                }
            }
        },
	}
</script>

<style lang="less">
	.import-files {
		height: 300px;
		padding: 20px 30px;
		.upload-area{
            flex-grow: 1;
			.ivu-upload{
				position: relative;
				height: 100%;
				width: 100%;
				background-color: #ebf5ff;
				border: none;
			}
			.upload-area-slot{
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				text-align: center;
				.iconfont{
					color: @color-Primary;
                    font-size: 60px;
				}
				.content-title{
                    margin-top: -5px;
					// line-height: 20px;
					color: @color-Content;
					font-size: 14px;
				}
				.content-text{
					// line-height: 17px;
					color: @color-Sub;
					font-size: 12px;
				}
            }
            
            &.is-step{
                position: relative;
                z-index: 1200;
                border: 1px dashed @color-Primary;
                &::before{
                    content: '';
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    top: 0;
                    left: 0;
                    border: 3px dashed white;
                    border-radius: 3px;
                    transform: scale(1.03, 1.1);
                }
                &::after{
                    content: '点击此处，选择在汽修软件中事先导出的Excel表单，打开，即上传维修数据成功！';
                    position: absolute;
                        top: -120px;
                        left: 50px;
                        padding: 30px;
                        border: 3px solid white;
                        font-size: 18px;
                        color: white;
                        font-weight: bold;
                        border-radius: 3px;
                        width: 740px;
                }
            }
		}
		.upload-list{
			width: 400px;
			height: 100%;
			margin-left: 20px;
			background-color: #f8f8f9;
			padding: 15px 0;
			display: flex;
			flex-direction: column;
			.list-title{
				color: #495060;
				font-size: 14px;
				margin-bottom: 5px;
				padding: 0 30px;
			}
			.list-content{
				overflow-y: auto;
				flex-grow: 1;
				padding: 0 30px;
				.list-item{
					margin-top: 10px;
					.item-detail{
						align-items: center;
						color: @color-Sub;
						font-size: 12px;
						line-height: initial;
						.iconfont{
							color: inherit;
						}
						.file-icon{

						}
						.file-name{
							flex-grow: 1;
							margin: 0 5px;
							color: inherit;
							font-size: inherit;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}
						.action-icon{
							width: 60px;
							text-align: right;
						}
					}
					
					.item-progress{
                        margin: 4px 0;
						.ivu-progress{
							display: flex;
							position: relative;
							height: 2px;
							.ivu-progress-outer{
								padding: 0;
								margin: 0;
								.ivu-progress-inner{
                                    display: block;
                                    background: #E9EAEC;
								}
							}
						}
					}
					.item-tip{
						color: rgba(237, 63, 20, 1);
						font-size: 12px;
					}
				}
			}
		}
	}
</style>